package com.example.wallpaper;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.example.wallpaper.databinding.FragmentWallViewBinding;
import com.example.wallpaper.model.Wallpaper;
import com.example.wallpaper.photoapi.DmoeCatch;
import com.example.wallpaper.vm.WallViewVM;

public class WallViewFragment extends Fragment {

    private static final String ARG1 = "wallpaper_img_url";

    private FragmentWallViewBinding mBinding;

    /**使用该方法对WallViewFragment进行实例化，该方式可以传参数*/
    public static WallViewFragment newInstance(String imgUrl){
        WallViewFragment fragment = new WallViewFragment();

        Bundle args = new Bundle();
        args.putString(ARG1,imgUrl);

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        String imgUrl = args.getString(ARG1);
        DmoeCatch dmoeCatch = new DmoeCatch();
        WallpaperViewHandler handler = new WallpaperViewHandler();
        dmoeCatch.getWallpaperView(handler,imgUrl);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_wall_view,container,false);
        return mBinding.getRoot();
    }

    private class WallpaperViewHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            byte[] args = bundle.getByteArray("args");
            //图片转换成位图
            Bitmap bitmap = BitmapFactory.decodeByteArray(args, 0, args.length);
            Drawable drawable = new BitmapDrawable(getResources(), bitmap);
            WallViewVM vm = new WallViewVM(getActivity().getApplication());
            vm.setDrawable(drawable);
            vm.setmBitmap(bitmap);
            mBinding.setWallViewVM(vm);
        }
    }
}
